package com.fyyg.common.converter;

import java.util.ArrayList;
import java.util.List;

import com.fyyg.common.page.PageData;
import com.fyyg.common.page.PageParam;
import com.fyyg.common.util.LogicUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class BaseConverterImpl implements IBaseConverter {


	private final static Logger log = LogManager.getLogger(BaseConverterImpl.class);


	@Override
	public <M, V> M convert2Model(V vo, Class<M> clazz) {
		if (LogicUtil.isNull(vo))
			return null;

		try {
			M model = clazz.newInstance();
			BeanCopyUtils.copyProperties(vo, model);
			return model;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("clazz new Instance error");
		}

		return null;
	}

	@Override
	public <M, V> V convert2Vo(M model, Class<V> clazz) {

		if (LogicUtil.isNull(model))
			return null;
		log.debug(model.toString());
		try {
			V vo = clazz.newInstance();
			BeanCopyUtils.copyProperties(model, vo);
			return vo;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("clazz new Instance error");
		}
		return null;
	}

	@Override
	public <M, V> List<V> convert2ListData(List<M> m, Class<V> clazz) {
		List<V> voList = new ArrayList<V>();
		if (LogicUtil.isNull(m)){
			return voList;
		}

		try {
			for (M model : m) {
				V vo = clazz.newInstance();
				BeanCopyUtils.copyProperties(model, vo);
				voList.add(vo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("clazz new Instance error");
		}
		return voList;
	}

	@Override
	public <M, V> PageParam<M> convert2PageParam(PageParam<V> page, Class<M> clazz) {
		if (LogicUtil.isNull(page) || LogicUtil.isNull(page.getP())) {
			return null;
		}
		try {
			PageParam<M> target = new PageParam<M>();
			M model = clazz.newInstance();
			BeanCopyUtils.copyProperties(page.getP(), model);
			target.setP(model);
			BeanCopyUtils.copyProperties(page, target, new String[] { "p" });
			return target;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("clazz new Instance error");
		}

		return null;
	}

	@Override
	public <M, V> PageData<V> convert2PageData(PageData<M> m, Class<V> clazz) {
		PageData<V> target = new PageData<V>();
		if (LogicUtil.isNull(m) || LogicUtil.isNullOrEmpty(m.getPageData()))
			return target;

		try {
			List<V> voList = new ArrayList<V>();
			for (M model : m.getPageData()) {
				V vo = clazz.newInstance();
				BeanCopyUtils.copyProperties(model, vo);
				voList.add(vo);
			}
			BeanCopyUtils.copyProperties(m, target, new String[] { "pageData" });
			target.setPageData(voList);

		} catch (Exception e) {
			e.printStackTrace();
			log.error("clazz new Instance error");
		}
		return target;
	}

}
